package com.wngbms.redisson;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyDefaultPromiseDemo {

    public static void main(String[] args) {

        NettyDefaultPromiseDemo promiseDemo = new NettyDefaultPromiseDemo();
        promiseDemo.methodA();

    }

    private static NioEventLoopGroup loopGroup = new NioEventLoopGroup(8);

    public void methodA() {
        log.info("method A start");
        Promise<String> promise = methodB("wngbms");

        promise.addListener(future -> {		// 1
            Object ret = future.get();      // 4. 此时可以直接拿到结果
            // 后续逻辑由 B 线程执行
            log.info("ret:{}",ret);
        });

        // A 线程不阻塞，继续执行其他代码...
        log.info("method A end");
    }

    public Promise<String> methodB(String name) {
//        return methodC(name);
        return methodD();
    }

    private Promise<String> methodD() {
        EventLoop eventLoop = loopGroup.next();
        eventLoop = loopGroup.next();

        Promise<String> promise = new DefaultPromise<>(eventLoop);
//        promise.setSuccess("hello windows");
        promise.trySuccess("hello windows");
        return promise;
    }

    private Promise<String> methodC(String name) {
        EventLoop eventLoop = loopGroup.next();
        eventLoop = loopGroup.next();
        Promise<String> promise = new DefaultPromise<>(eventLoop);

        loopGroup.schedule(() -> {		// 2
            log.info("execute");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("execute success");
            promise.setSuccess("hello " + name);	// 3
        }, 0, TimeUnit.SECONDS);

        return promise;
    }


}